package org.firebug.spring.boot.transaction.service;

import org.firebug.spring.boot.transaction.repository.dao.AccountDAO;
import org.firebug.spring.boot.transaction.repository.po.AccountPO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class AccountService {
    @Resource
    private AccountService accountService;
    @Resource
    private AccountDAO accountDAO;

    /** 转帐 */
    @Transactional
    public void transfer(int fromAccountId, int toAccountId, double money) {
        AccountPO fromAccount = accountDAO.selectById(fromAccountId);
        AccountPO toAccount = accountDAO.selectById(toAccountId);
        accountService.transfer(fromAccount, toAccount, money);
    }

    /** 转帐 */
    @Transactional
    public void transfer(AccountPO fromAccount, AccountPO toAccount, double money) {
        accountService.withdraw(fromAccount, money);
        accountService.deposit(toAccount, money);
    }

    /** 存钱 */
    @Transactional
    public void deposit(AccountPO account, double money) {
        if(account == null) {
            throw new RuntimeException("账户不存在");
        }
        accountDAO.increaseBalanceById(account.getId(), money);
    }

    /** 取钱 */
    @Transactional
    public void withdraw(AccountPO account, double money) {
        if(account == null) {
            throw new RuntimeException("账户不存在");
        }
        if(account.getBalance() < money) {
            throw new RuntimeException("账户余额不足");
        }
        accountDAO.decreaseBalanceById(account.getId(), money);
    }
}
